package com.mzj.saas.rent;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.repository.core.AjaxResult;
import com.haixiaoke.saas.repository.exception.BizException;
import com.haixiaoke.saas.repository.pojo.HousingAllocation;
import com.haixiaoke.saas.repository.pojo.Order;
import com.haixiaoke.saas.repository.service.IHouseKeeperService;
import com.haixiaoke.saas.repository.service.IHousingAllocationService;
import com.haixiaoke.saas.repository.service.IOrderPasswordRecordService;
import com.haixiaoke.saas.repository.service.impl.OrderServiceImpl;
import com.mzj.saas.annotation.CheckAuth;
import com.mzj.saas.annotation.RepeatSubmit;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.service.LockAppService;
import com.mzj.saas.mservice.property.entity.CommunityHouseUser;
import com.mzj.saas.mservice.property.service.CommunityHouseUserService;
import com.mzj.saas.mservice.property.vo.MatchUserHouseVO;
import com.mzj.saas.mservice.property.vo.SaveOrEditVO;
import com.mzj.saas.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 房管家Controller
 *
 * @author qixi
 * @date 2023-04-14
 */
@Slf4j
@RestController
@RequestMapping("/house/keeper")
public class HouseKeeperController {

    @Autowired
    private IHouseKeeperService houseKeeperService;
    @Autowired
    private LoginUserUtil loginUserUtil;
    @Autowired
    private CommunityHouseUserService communityHouseUserService;
    @Autowired
    private OrderServiceImpl orderService;
    @Autowired
    private LockAppService lockAppService;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private IHousingAllocationService housingAllocationService;

    @Autowired
    private IOrderPasswordRecordService iOrderPasswordRecordService;


    /**
     * 入住
     *
     * @return
     */
    @GetMapping("/toStayIn/{orderId}")
    @CheckAuth
    @RepeatSubmit
    public AjaxResult toStayIn(@PathVariable("orderId") String orderId) {
        System.out.println("办理入住start");
        String token = loginUserUtil.getToken();
        Order order = orderService.selectOrderById(orderId);
        String houseId = order.getHouseId();

        //校验订单状态
        if (Order.ORDER_STATE_PAYMENT != order.getOrderState()) {
            throw new BizException(50001, "订单状态异常!");
        }

        Date checkInTime = order.getCheckInTime();
        if (checkInTime.getTime() > System.currentTimeMillis()) {
            Integer code = Convert.toInt(StatusCode.ERROR_CODE_10001.getErrorCode());
            return AjaxResult.error(code, "未到预定时间,无法入住!");
        }

        if (order.getCheckOutTime().before(new Date())) {
            Integer code = Convert.toInt(StatusCode.ERROR_CODE_10001.getErrorCode());
            return AjaxResult.error(code,"该订单已逾期，无法入住！");
        }

        HousingAllocation housingAllocation = housingAllocationService.selectHousingAllocationById(order.getAllocationId());
        if (HousingAllocation.CLEANING_TYPE_NO.equals(housingAllocation.getCleaningType())) {
            return AjaxResult.error("房屋打扫中，请联系客服人员！");
        }

        //手动控制事务
        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
        try {

            //新增判断房屋是否存在承租人，如果存在不给予入住；
            List<CommunityHouseUser> communityHouseUserList = communityHouseUserService.findByCommunityHouseIdAndStatusAndType(houseId,1,1);
            if (CollectionUtil.isNotEmpty(communityHouseUserList)) {
                return AjaxResult.error("当前房屋不可入住，请联系管家处理");
            }

            addOrEdit(orderId);
            houseKeeperService.toStayIn(orderId);

            // todo 演示关闭锁调用接口
            ResultBean<Object> resultBean = lockAppService.authOpenDoor(token, houseId, 30, 1);
            String code = resultBean.getCode();
            String msg = resultBean.getMsg();

            if (StatusCode.SUCCESS_CODE_10000.getErrorCode().equals(code)) {
                platformTransactionManager.commit(transactionStatus);
                return AjaxResult.success("入住成功" + msg);
            } else {
                platformTransactionManager.rollback(transactionStatus);
                System.out.println("事务回滚");
                System.out.println("授权临时密码失败");
                return AjaxResult.error(msg);
            }

        } catch (Exception e) {
            System.out.println("捕获异常，事务回滚");
            platformTransactionManager.rollback(transactionStatus);
            throw new BizException("当前房屋不可入住，请联系管家处理", e);
        } finally {
            System.out.println("办理入住end");
        }

    }

    /**
     * 退租
     *
     * @return
     */
    @GetMapping("/renunciation/{orderId}")
    @CheckAuth
    @RepeatSubmit
    public AjaxResult renunciation(@PathVariable("orderId") String orderId) {
        return houseKeeperService.renunciation(orderId);
    }

    /**
     * 续租
     *
     * @return
     */
    @GetMapping("/reletting")
    @CheckAuth
    public AjaxResult reletting(@RequestParam(value = "orderId", required = true) String orderId,
                                @RequestParam(value = "reletOrderId", required = true) String reletOrderId) {
        return houseKeeperService.reletting(orderId, reletOrderId);
    }


    /**
     * 成员登记
     *
     * @param orderId
     */
    @RepeatSubmit
    private void addOrEdit(String orderId) {
        System.out.println("成员登录 start");
         String token = loginUserUtil.getToken();
        Order order = orderService.selectOrderById(orderId);
        Integer errorCode = Convert.toInt(StatusCode.ERROR_CODE_10001.getErrorCode());
        if (order == null || !Order.ORDER_STATE_PAYMENT.equals(order.getOrderState())) {
            throw new BizException(errorCode, "订单状态异常！");
        }

        SaveOrEditVO vo = new SaveOrEditVO();
        vo.setMatchType(1);

        //房产成员信息
        List<CommunityHouseUser> communityHouseUsers = new ArrayList<>();
        CommunityHouseUser communityHouseUser = new CommunityHouseUser();
        communityHouseUser.setCommunityHouseId(order.getHouseId());
        communityHouseUser.setCommunityId(order.getResidenceCommunityId());
        communityHouseUser.setMobile(order.getReservationPhone());
        communityHouseUser.setName(order.getReservationName());
        communityHouseUser.setType(1);
        communityHouseUser.setUserType(2);
        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_YES);
        communityHouseUser.setOrderId(orderId);
        communityHouseUsers.add(communityHouseUser);
        //承租人与房屋关系
        MatchUserHouseVO matchUserHouseVO = new MatchUserHouseVO();
        matchUserHouseVO.setChargeMode(1);
        matchUserHouseVO.setStartDate(order.getCheckInTime());
        matchUserHouseVO.setEndDate(order.getCheckOutTime());
        matchUserHouseVO.setHouseId(order.getHouseId());
        matchUserHouseVO.setLabel(1);

        vo.setHouseIds(order.getHouseId());
        vo.setCommunityHouseUsers(communityHouseUsers);
        vo.setMatchUserHouseVO(matchUserHouseVO);
        ResultBean<Object> result = communityHouseUserService.addOrEditUser(token, vo);


        String code = result.getCode();
        if (StrUtil.isEmpty(code) || !StatusCode.SUCCESS_CODE_10000.getErrorCode().equals(code)) {
            throw new BizException(errorCode, "成员登记异常！");
        }
        System.out.println("成员登记 end");
    }


}
